package com.thinkfit.jy.view;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.thinkfit.jy.R;
import com.thinkfit.jy.adapter.DownloadAdapter;
import com.thinkfit.jy.presenter.ApplicationPresenter;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.DialogViewUtils;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.FileUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.SystemUtils;
import com.thinkfit.jy.utils.Utils;
import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.Error;
import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchConfiguration;
import com.tonyodev.fetch2.FetchListener;
import com.tonyodev.fetch2.Request;
import com.tonyodev.fetch2core.DownloadBlock;

import java.io.File;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 应用列表
 */
public class ApplicationView implements View.OnClickListener {

    private static ApplicationView applicationView;
    WindowManager windowManager;
    Context mContext;
    boolean isFist = true;
    View inflate;
    WindowManager.LayoutParams layoutParams;
    RelativeLayout rl;
    LinearLayout llApplicationBack;
    RecyclerView recyclerView;
    DownloadAdapter downloadAdapter;
    Fetch fetch;

    ConcurrentHashMap<String, DownloadAdapter.DownloadData> installMap = new ConcurrentHashMap<>();
    ConcurrentHashMap<String, Boolean> installedMap = new ConcurrentHashMap<>();
    String installKey = "";
    boolean isInstall = false;
    DownloadAdapter.DownloadData installValue = null;
    public static ApplicationView getInstance(){
        if(applicationView == null){
            applicationView = new ApplicationView();
        }
        return applicationView;
    }

    public void initView(Context context,boolean isVisibility){
        mContext = context;
        if(windowManager == null){
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        if(inflate == null){
            inflate = LayoutInflater.from(context).inflate(R.layout.activity_application, null);
            rl = inflate.findViewById(R.id.rl);
            llApplicationBack = inflate.findViewById(R.id.ll_application_back);
            recyclerView = inflate.findViewById(R.id.recyclerView);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 5);
            gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(gridLayoutManager);
//            getAdapter().onAttachedToRecyclerView(recyclerView);
//        recyclerView.setAdapter(getAdapter());
            recyclerView.setAdapter(downloadAdapter);

            initFetch();
            if(downloadAdapter == null){
                downloadAdapter = new DownloadAdapter(new DownloadAdapter.ActionListener() {
                    @Override
                    public void onPauseDownload(int id) {
                        fetch.pause(id);
                    }

                    @Override
                    public void onResumeDownload(int id) {
                        fetch.resume(id);
                    }

                    @Override
                    public void onRemoveDownload(int id) {
                        fetch.remove(id);
                    }

                    @Override
                    public void onRetryDownload(int id) {
                        fetch.retry(id);
                    }
                });

                downloadAdapter.setOnClick(new DownloadAdapter.Click() {
                    @Override
                    public void click(View v,DownloadAdapter.DownloadData downloadData,int position) {
                        switch (v.getId()){
                            case R.id.ivUninstall:
                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    delete "+downloadData.packageName);
                                Intent intent2 = new Intent(Intent.ACTION_DELETE);
                                intent2.setData(Uri.parse("package:" + downloadData.packageName));
                                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                mContext.startActivity(intent2);
                                downloadData.isState = false;
                                downloadData.isDelete = true;
                                downloadAdapter.notifyItemChanged(position);
                                break;
                            case R.id.downButton:
                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    startDownload "+downloadData.packageName);
                                downloadData.isState = true;
                                startDownload(downloadData,position);
                                break;
                            case R.id.ivIcon:
                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    open : "+downloadData.packageName);
                                intent2 = mContext.getPackageManager().getLaunchIntentForPackage(downloadData.packageName);
//                        intent2.setData(Uri.parse("package:" + downloadData.packageName));
//                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                mContext.startActivity(intent2);
                                break;

                        }

                    }
                });
            }

            llApplicationBack.setOnClickListener(this);

        }



        if(layoutParams == null){
            layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );

//            layoutParams.gravity = Gravity.CENTER;
            layoutParams.gravity = Gravity.TOP| Gravity. CENTER;
        }


        if(isFist){
            isFist = false;
            windowManager.addView(inflate,layoutParams);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }
        if(isVisibility){
            inflate.setVisibility(View.VISIBLE);
        }else {
            inflate.setVisibility(View.GONE);
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_application_back:
                goneButton();
                break;
        }

    }

    public void  initFetch(){
        if (fetch == null) {
            FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(mContext)
                    .enableRetryOnNetworkGain(true)
                    .setDownloadConcurrentLimit(2)
//                    .setHttpDownloader(new OkHttpDownloader(Downloader.FileDownloaderType.PARALLEL))
                    .enableAutoStart(false)
//                    .setHttpDownloader(new HttpUrlConnectionDownloader(Downloader.FileDownloaderType.PARALLEL))
                    .build();

            fetch = Fetch.Impl.getInstance(fetchConfiguration);

            fetch.addListener(fetchListener);
        }

    }

    FetchListener fetchListener = new FetchListener() {

        @Override
        public void onAdded(@NonNull Download download) {
            int position = downloadAdapter.getUrlPosition(download.getUrl());
            DownloadAdapter.DownloadData downloadData = downloadAdapter.getData().get(position);
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   position  "+position+"  , packageName : "+downloadData.packageName);
            if(downloadData != null){
                if(download != null){
                    downloadData.downloadId = download.getId();
                    downloadData.download = download;
                    downloadData.downloadPath = FileUtils.getDownloadPath(mContext);
                    System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   downloadData  "+downloadData.toString());
//                    downloadAdapter.addDownload(downloadData);
                    downloadAdapter.notifyItemChanged(position);
                }
            }
        }
        @Override
        public void onQueued(@NonNull Download download, boolean b) {
            if (downloadAdapter != null) {
                int position = downloadAdapter.getPosition(download);
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   onQueued.position  "+position);
                downloadAdapter.setStartAndPausedVisibility(true,position);
                downloadAdapter.setRemovedVisibility(true,position);
                downloadAdapter.setProgressVisibility(true,position);
                downloadAdapter.setDownVisibility(false,position);
                downloadAdapter.update(download, -1, 0);
            }
        }
        @Override
        public void onWaitingNetwork(@NonNull Download download) {

        }
        @Override
        public void onCompleted(@NonNull Download download) {
            File file = new File(download.getFile());
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  tempFile =  "+file.exists());
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  download.getFile =  "+download.getFile());
            List<DownloadAdapter.DownloadData> data = downloadAdapter.getData();
            if(file.exists() && file.isFile()){
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  下载完成");
                int position = downloadAdapter.getPosition(download);
                downloadAdapter.setDownVisibility(false,position);
                downloadAdapter.setStartAndPausedVisibility(false,position);
                downloadAdapter.setRemovedVisibility(true,position);
                downloadAdapter.setProgressVisibility(false,position);
                downloadAdapter.downloadSucceed(true,position);
                downloadAdapter.setInstallProgressVisibility(true,position);

                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  data.size : "+data.size());
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  position : "+position);
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  isAvilible : "+isAvilible(mContext,data.get(position).packageName));
//                if(data.get(position).versionCode > SystemUtils.getVersion(getContext(),data.get(position).packageName)){
//
//                }
//                downloadAdapter.setInstallProgressVisibility(true,position);
                ToastUtils.showShort("应用安装中");
                downloadAdapter.setStateText("安装中",position);

                install(data.get(position));

            }
        }
        @Override
        public void onError(@NonNull Download download, @NonNull Error error, @Nullable Throwable throwable) {
            throwable.printStackTrace();
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }
        @Override
        public void onDownloadBlockUpdated(@NonNull Download download, @NonNull DownloadBlock downloadBlock, int i) {

        }

        @Override
        public void onStarted(@NonNull Download download, @NonNull List<? extends DownloadBlock> list, int i) {

        }
        @Override
        public void onProgress(@NonNull Download download, long l, long l1) {
            if (downloadAdapter != null) {
                downloadAdapter.setProgressVisibility(true,downloadAdapter.getPosition(download));
                downloadAdapter.update(download, l, l1);
            }
        }
        @Override
        public void onPaused(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

        @Override
        public void onResumed(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

        @Override
        public void onCancelled(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

        @Override
        public void onRemoved(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
                int position = downloadAdapter.getPosition(download);
                downloadAdapter.setStateText("",position);
            }
        }



        @Override
        public void onDeleted(@NonNull Download download) {
            if (downloadAdapter != null) {
                downloadAdapter.update(download, -1, 0);
            }
        }

    };


    public boolean isAvilible(Context context, String packageName) {
        //1.PackageManager 包的管理者对象
        PackageManager pm = context.getPackageManager();
        //2.获取应用的配置信息,在此处传递0获取的是基本信息(包名,版本名称,版本号)
        try {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
            if(packageName.equals(packageInfo.packageName)){
                return true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;

    }

    public void install(DownloadAdapter.DownloadData downloadData){
//        AppInstallTask.Builder builder = new AppInstallTask.Builder();
//        builder.addInstallation(new AppInstallTask.Installation(
//                downloadData.packageName,
//                downloadData.versionCode,
//                downloadData.url,
//                downloadData.downloadPath,
//                downloadData.downloadFileName
//        ));
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   packageName : "+downloadData.packageName);
        synchronized (installMap){
            if(!installMap.containsKey(downloadData.packageName)){
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   packageName : "+downloadData.packageName);
                installMap.put(downloadData.packageName, downloadData);
            }
            if(!installedMap.containsKey(downloadData.packageName)){
                installedMap.put(downloadData.packageName, false);
            }
        }

//        if(delQueryInstallDispose != null&&!installDisposable.isDisposed() ){
//            return;
//        }

        String packageName = downloadData.packageName;
        ToastUtils.showShort(mContext.getString(R.string.app_application_installing)+" : " + packageName);
        installNotify();
    }

    public void installNotify() {
        if (isInstall) {
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  installNotify 有安装正在进行");
            return;
        }
        installValue = null;
        installKey = "";
        synchronized (installMap){
            for (String key : installMap.keySet()) {
                installKey = key;
                installValue = installMap.get(key);
                break;
            }
            if (installValue != null) {
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa installNotify : " + installValue.name + "：" + installValue.packageName);
//                addInstallView(StringUtils.isEmpty(installValue.getAppName()) ? installValue.getPackageName() : installValue.getAppName());
            }
        }
        SystemUtils.getInstance().installApk(mContext,
                new File(installValue.downloadPath+ installValue.downloadFileName));
        isInstall = true;
        installMap.remove(installValue.packageName);
//        Observable.create(new ObservableOnSubscribe<String>() {
//                    @Override
//                    public void subscribe(ObservableEmitter<String> emitter) throws Exception {
//                        try {
//                            if(installValue != null){
//                                System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify 开始安装" + installKey);
//                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   安装路径 :"+ installValue.downloadPath+ installValue.downloadFileName);
//                                AppCommHelper mAppCommHelper = new AppCommHelper();
//                                boolean install = mAppCommHelper.silentInstallApp(installValue.downloadPath+ installValue.downloadFileName);
////                                SystemOperateUtil.getInstance().getSystemOperate().silentInstall(installValue.getDownloadPath());
////                                SystemOperateUtil.getInstance().getSystemOperate().installAppC(installValue);
//                                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   安装结果 :"+install);
//                                if(install){
//                                    if(!emitter.isDisposed()){
//                                        emitter.onNext(installKey);
//                                    }
//                                }else {
//                                    System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify 开始安装" + installKey + "异常");
//                                    disposeInstall();
//                                }
//                            }
//
//                        }catch (Exception e){
//                            e.printStackTrace();
//                            System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify 开始安装" + installKey + "异常");
//                            disposeInstall();
//                        }
//                    }
//                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<String>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        installDisposable = d;
//                    }
//
//                    @Override
//                    public void onNext(String aBoolean) {
//                        getRootView().installOver(aBoolean);
//                        installMap.remove(aBoolean);
//                        installedMap.remove(aBoolean);
//                        refreshMap.put(aBoolean,true);
//                        ToastUtils.showShort(aBoolean + "安装完成");
//                        System.out.println(  "aaaaaaaaaaaaaaaaaaaaaaaaa installNotify " + aBoolean + "安装完成");
//                        deleyTime();
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        disposeInstall();
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        disposeInstall();
//                    }
//                });
    }
    public void startDownload(DownloadAdapter.DownloadData downloadData,int position){
        String file = FileUtils.getDownloadPath(mContext)+ downloadData.downloadFileName;
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  click.position  : "+position);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  file  : "+file);

//                downloadAdapter.setStateText("准备下载中",position);
        File file1 = new File(file);
        if(file1.exists() && file1.isFile()){
            file1.delete();
        }

        String url = downloadData.url;
        Request request = new Request(url, file);
        fetch.enqueue(request, request1 -> {
            //Request enqueued for download
        }, error -> {
            //Error while enqueuing download
        });
    }

    public void setAppAdapterData(List<DownloadAdapter.DownloadData> list){
        System.out.println("aaaaaaaaaaaaaaaaaaaaaa     setAppAdapterData ");
        if(downloadAdapter != null){
            System.out.println("aaaaaaaaaaaaaaaaaaaaaa     list  : "+list.size());
            for (DownloadAdapter.DownloadData downloadData : list){
                downloadAdapter.addDownload(downloadData);
            }
            downloadAdapter.notifyDataSetChanged();

        }
    }

    public void visibleLayout(){
        if(windowManager != null){
            if(inflate != null){
                inflate.setVisibility(View.VISIBLE);
            }
        }
    }

    public void goneButton(){
        System.out.println("aaaaaaaaaaaaaaaaaaaaaa     goneButton ");
        if(windowManager != null){
            if(inflate != null){
                inflate.setVisibility(View.GONE);
            }
        }

    }



    /**
     * dp2px
     */
    protected int dp2px(float dpValue) {
        float density = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }


}
